using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using GifComponents;

namespace BardsTaleViewer {
  public static class Gif {
    //public static void CreateAnimatedGif (Bitmap bitmap1, Bitmap bitmap2) {
    //  AnimatedGifEncoder e = new AnimatedGifEncoder ();
    //  e.Start ("test.gif");
    //  e.SetDelay (500);
    //  e.SetRepeat (0);
    //  e.AddFrame (bitmap1);
    //  e.AddFrame (bitmap2);
    //  e.Finish ();
    //}

    public static void CreateAnimatedGif (IPicture picture, string fileName, int bardVersion) {
      AnimatedGifEncoder e = new AnimatedGifEncoder ();
      e.Transparent = Color.Empty;
      e.RepeatCount = 0;
      e.ColourQuality = 1;
      e.QuantizerType = QuantizerType.Octree;
      e.ColourTableStrategy = ColourTableStrategy.UseGlobal;
      //GifFrame frame1 = new GifFrame (bitmap1);
      //frame1.Delay = 150;
      //GifFrame frame2 = new GifFrame (bitmap2);
      //frame2.Delay = 50;

      bool cut = false;
      int animsPeriodMax = Form1.ComputeAnimPeriodMax (picture.Anims);

      PicturePlayer player = new PicturePlayer (picture);
      int delay = (int) Math.Round (Form1.GetDelay (bardVersion) / 10.0);
      int nbFrames = 60 * 100 / delay;
      //Bitmap bitmapPrev = null;
      GifFrame framePrev = null;

      nbFrames = animsPeriodMax;
      int nbFramesFinal = 0;
      for (int i = 0; i < nbFrames; i++) {
        Bitmap bitmap = player._bitmap;
        GifFrame frame = null;
        if ((framePrev != null) && (bitmap.IsSame ((Bitmap) framePrev.TheImage)))
          //frame = framePrev;
          framePrev.Delay += delay;
        else {
          frame = new GifFrame (bitmap.Copy ());
          frame.Delay = delay;
          e.AddFrame (frame);
          framePrev = frame;
          nbFramesFinal++;
          if (nbFramesFinal == 128) {
            cut = true;
            break;
          }
        }
        //bitmap.Save ("Test " + i.ToString ().PadLeft (3, '0') + ".png", System.Drawing.Imaging.ImageFormat.Png);

        player.Tick ();
        //bitmapPrev = bitmap;
      }

      //if (cut)
      //  fileName += " CUT";
      fileName += ".gif";
      e.WriteToFile (fileName);
    }
  }
}
